import 'dart:developer' as developer;
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'ring_service.dart';

/// 设备SN管理服务
/// 统一管理设备序列号，支持自动保存和恢复
class DeviceSnManager extends GetxService {
  static const String _tag = 'DeviceSnManager';
  
  // 存储键名
  static const String _keyDeviceSn = 'current_device_sn';
  
  late final SharedPreferences _prefs;
  
  // 响应式状态 - 当前设备SN
  final RxString _currentDeviceSn = ''.obs;
  
  // Getters
  String get currentDeviceSn => _currentDeviceSn.value;
  RxString get currentDeviceSnRx => _currentDeviceSn;
  
  // 单例模式
  static DeviceSnManager? _instance;
  
  static DeviceSnManager get instance {
    _instance ??= Get.find<DeviceSnManager>();
    return _instance!;
  }

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializeStorage();
    await _loadStoredDeviceSn();
    developer.log('📱 设备SN管理服务初始化完成', name: _tag);
  }

  /// 初始化存储
  Future<void> _initializeStorage() async {
    try {
      _prefs = await SharedPreferences.getInstance();
      developer.log('✅ 存储初始化成功', name: _tag);
    } catch (e) {
      developer.log('❌ 存储初始化失败: $e', name: _tag);
    }
  }

  /// 加载存储的设备SN
  Future<void> _loadStoredDeviceSn() async {
    try {
      final storedSn = _prefs.getString(_keyDeviceSn);
      if (storedSn != null && storedSn.isNotEmpty) {
        _currentDeviceSn.value = storedSn;
        developer.log('📱 已加载存储的设备SN: $storedSn', name: _tag);
      } else {
        developer.log('📱 未找到存储的设备SN', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 加载设备SN失败: $e', name: _tag);
    }
  }

  /// 保存设备SN（从蓝牙连接获取）
  Future<void> saveDeviceSn(String deviceSn) async {
    try {
      if (deviceSn.isEmpty) {
        developer.log('⚠️ 尝试保存空的设备SN，已忽略', name: _tag);
        return;
      }
      
      _currentDeviceSn.value = deviceSn;
      await _prefs.setString(_keyDeviceSn, deviceSn);
      developer.log('💾 设备SN已保存: $deviceSn', name: _tag);
    } catch (e) {
      developer.log('❌ 保存设备SN失败: $e', name: _tag);
    }
  }

  /// 清除设备SN
  Future<void> clearDeviceSn() async {
    try {
      _currentDeviceSn.value = '';
      await _prefs.remove(_keyDeviceSn);
      developer.log('🗑️ 设备SN已清除', name: _tag);
    } catch (e) {
      developer.log('❌ 清除设备SN失败: $e', name: _tag);
    }
  }

  /// 获取设备SN（优先使用当前连接的设备，否则使用存储的SN）
  String getDeviceSn() {
    try {
      // 优先尝试从RingService获取当前连接设备的SN
      final ringService = Get.find<RingService>();
      if (ringService.isConnected) {
        final connectedDevice = ringService.connectedDevice;
        if (connectedDevice != null && connectedDevice.deviceSn.isNotEmpty) {
          // 如果当前连接的设备SN与存储的不同，更新存储
          if (connectedDevice.deviceSn != _currentDeviceSn.value) {
            saveDeviceSn(connectedDevice.deviceSn);
          }
          return connectedDevice.deviceSn;
        }
      }
    } catch (e) {
      developer.log('⚠️ 无法从RingService获取设备SN: $e', name: _tag);
    }

    // 如果没有连接，返回存储的SN
    if (_currentDeviceSn.value.isNotEmpty) {
      developer.log('📱 使用存储的设备SN: ${_currentDeviceSn.value}', name: _tag);
      return _currentDeviceSn.value;
    }

    developer.log('⚠️ 未找到可用的设备SN', name: _tag);
    return '';
  }

  /// 检查是否有可用的设备SN
  bool hasDeviceSn() {
    return getDeviceSn().isNotEmpty;
  }
}
